package com.wbao.dianniu.http;

import java.io.IOException;
import java.io.Serializable;

import org.apache.http.Header;
import org.apache.http.ParseException;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.alibaba.mobileim.channel.IMChannel;
import com.alibaba.wxlib.util.SysUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.ui.LoginActivity;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;

public class HttpUtil implements Serializable {
    private static final String TAG = HttpUtil.class.getSimpleName();
    /**
     * 系列化
     */
    private static final long serialVersionUID = 3479064155440582563L;
    //server ip url
    private String url = "http://api.dianniuapp.com/";
    // test server url
    private String test_url = "http://118.178.189.156:8080/dianniu/batch/json";
    //    private String test_url = "http://192.168.1.10:8080/dianniu/batch/json";
    private String contentType = "application/json";
    private Dialog pDialog;


    public interface MyResponse {
        void responseSucess(Object obj);

        void responseFailure(int errorCode, String msg);
    }

    public void req(Context context, StringEntity entity, MyResponse response) {
        req(context, entity, false, response);
    }

    public void req(Context context, StringEntity entity, boolean isShowWaitting, MyResponse resp) {
        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(10000);// 设置链接超时，如果不设置，默认为10s
        String reqStr = "";
        try {
            reqStr = EntityUtils.toString(entity, "UTF-8");
            System.out.println("请求内容：" + reqStr);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        IMChannel.DEBUG = Boolean.valueOf(SysUtil.isDebug());
        if (IMChannel.DEBUG) {
            // 连接到测试平台
            url = test_url;
        }

//        url = test_url;

        if (isShowWaitting) {
            pDialog = LoadingDialog.createLoadingDialog(context, "正在加载中...");
            pDialog.show();
        }
        client.post(context, url, entity, contentType, new MyHttpResponseHandler(context, reqStr, resp, isShowWaitting));
    }

    private class MyHttpResponseHandler extends JsonHttpResponseHandler {
        private boolean isShowing;
        private MyResponse resp;
        private Context mContext;
        private String reqStr;

        public MyHttpResponseHandler(Context context, String reqString, MyResponse resp, boolean isShowing) {
            mContext = context;
            this.isShowing = isShowing;
            this.resp = resp;
            this.reqStr = reqString;
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (isShowing) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
            }
            Notification.toast(mContext, mContext.getResources().getString(R.string.link_fails));
            resp.responseFailure(statusCode, mContext.getResources().getString(R.string.link_fails));
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            if (isShowing) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
            }
            Notification.toast(mContext, mContext.getResources().getString(R.string.link_fails));
            resp.responseFailure(statusCode, mContext.getResources().getString(R.string.link_fails));
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            if (isShowing) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
            }
            // 接收到数据 传递给obj
            if (statusCode == ErrorCode.RETURN_OK) {
                System.out.println("应答内容：" + response.toString());
                RespJsonData data = new RespJsonData();
                try {
                    data = JsonUtil.getJson().fromJson(response.toString(), RespJsonData.class);
                    int retCode = data.getReturn_code();
                    if (retCode == 800) {    // 单独处理800错误  token已过期 重新登录
                        String return_msg = data.getReturn_msg();
                        MobclickAgent.reportError(mContext, "请求内容：" + reqStr + "\n 返回结果：" + response.toString());
                        Notification.toast(mContext, return_msg);
                        GlobalContext.cleanCacheToken();
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setClass(mContext, LoginActivity.class);
                        mContext.startActivity(intent);

                    } else if (retCode == 0) {
                        resp.responseSucess(data.getReturn_data());
                    } else {
                        MobclickAgent.reportError(mContext, "请求内容：" + reqStr + "\n 返回结果：" + response.toString());
//                        Notification.toast(mContext, data.getReturn_msg());
                        resp.responseFailure(retCode, data.getReturn_msg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d(TAG, "错误信息：" + "请求内容：" + reqStr + "\n 返回结果：" + e.getMessage());
                    MobclickAgent.reportError(mContext, e);
                    Notification.toast(mContext, mContext.getResources().getString(R.string.data_error));
                }

            }
        }

    }


    public static void logAll(String tag, String msg) {
        int LENGTH = 4000;
        if (msg.length() > LENGTH) {
            for (int i = 0; i < msg.length(); i += LENGTH) {
                if (i + LENGTH < msg.length()) {
//                    System.out.println(tag + msg.substring(i, i + LENGTH));
                } else {
//                    System.out.println(tag + msg.substring(i, msg.length()));
                }
            }
        } else {
//            System.out.println(tag + msg);
        }
    }


}
